package com.tiyende.credit.loop.base

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.IBinder
import android.view.KeyEvent
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.FrameLayout
import androidx.appcompat.app.AppCompatActivity
import com.tiyende.credit.loop.R
import com.tiyende.credit.loop.base.app.TiyendeActivityStackManager
import com.tiyende.credit.loop.databinding.TiyendeParentViewBinding
import com.tiyende.credit.loop.ui.activity.TiyendeLaunchActivity
import com.tiyende.credit.loop.ui.dialog.TiyendeLoading
import com.tiyende.credit.loop.utils.TiyendeTitleBarUtil
import com.tiyende.credit.loop.utils.TiyendeToastManager
import com.tiyende.credit.loop.utils.log.TiyendeLogger

/**
 * BaseActivity
 * @Author wwdeng
 * @CreateTime: 2024/11/22 10:32
 * @Annotation：基类 Activity
 */
abstract class BaseActivity : AppCompatActivity(), IBaseView {

    lateinit var rootViewBinding: TiyendeParentViewBinding

    /* 是否拦截返回按钮，默认不拦截直接返回 */
    private var isInterceptBack = false
    /* 点击外部是否需要隐藏软键盘 */
    private var isHideSoftInput = true

    /* 退出程序提示 */
    private var mExitTips = "Press again to exit the app"
    //是否被系统回收
    var isRecreated = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (savedInstanceState != null){
            isRecreated = true
        }
        if (savedInstanceState != null && this::class.java.simpleName != TiyendeLaunchActivity::class.java.simpleName){
            onIntent(TiyendeLaunchActivity::class.java)
            return
        }
        isRecreated = false
        TiyendeTitleBarUtil.transparentStatusBar(this)
        TiyendeTitleBarUtil.setStatusBarLightMode(this, false)
        setContentView(getTiyendeRootView())
        initTiyendeView()
        initTiyendeListener()
        loadTiyendeData()
    }

    private var hasLoadedData = false
    override fun onResume() {
        super.onResume()
        if (!hasLoadedData) {
//            loadTiyendeData()
            hasLoadedData = true
        }
    }

    protected abstract fun getTiyendeRootView(): View?

    protected abstract fun initTiyendeView()

    protected abstract fun initTiyendeListener()

    protected abstract fun loadTiyendeData()

    /**
     * 重试
     */
    protected abstract fun requestTryAgain()

    override fun setContentView(rootView: View?) {
        rootViewBinding = TiyendeParentViewBinding.inflate(layoutInflater)
        rootViewBinding.rootTitleBar.setPadding(0, TiyendeTitleBarUtil.getStatusBarHeight(),0,0)
        if (rootView != null){
            rootViewBinding.rootContainer.addView(rootView, FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))
        }
        setTiyendeTitleBarVisibility(View.GONE)
        setTiyendeRootParentBackgroundResource(R.mipmap.tiyende_root_bg)
        //返回
        rootViewBinding.rootBack.setOnClickListener {
            onBackAction()
        }
        super.setContentView(rootViewBinding.root)
    }

    /**
     * 设置背景透明
     */
    fun setTiyendeRootParentTransparent(){
        setTiyendeRootParentBackgroundColor(getColor(R.color.transparent))
    }

    /**
     * 设置背景颜色
     */
    private fun setTiyendeRootParentBackgroundColor(color: Int){
        rootViewBinding.rootLayout.setBackgroundColor(color)
//        rootViewBinding.rootLayout.setBackgroundColor(color)
    }

    /**
     * 设置背景图片
     */
    private fun setTiyendeRootParentBackgroundResource(drawableId: Int){
        rootViewBinding.rootLayout.setBackgroundResource(drawableId)
    }

    /**
     * @功能描述：是否显示Toolbar
     */
    fun setTiyendeTitleBarVisibility(visibility: Int) {
        rootViewBinding.rootTitleBar.visibility = visibility
    }

    /**
     * 设置toolBar背景颜色
     */
    fun setTiyendeTitleBarColor(color: Int) {
        setTiyendeTitleBarVisibility(View.VISIBLE)
        rootViewBinding.rootTitleBar.setBackgroundColor(color)
    }

    /**
     * 设置toolBar背景图片
     */
    fun setTiyendeTitleBarRes(res: Int) {
        setTiyendeTitleBarVisibility(View.VISIBLE)
        rootViewBinding.rootTitleBar.setBackgroundResource(res)
        rootViewBinding.rootTitleBar.setPadding(0, 0, 0, 0)
    }

    /**
     * 设置是否显示返回
     */
    fun setTiyendeBackBtnVisibility(visibility: Int) {
        rootViewBinding.rootBack.visibility = visibility
    }

    /**
     * 设置返回按钮图标
     */
    fun setTiyendeBackBtnRes(res: Int){
        setTiyendeBackBtnVisibility(View.VISIBLE)
        rootViewBinding.rootBack.setImageResource(res)
    }

    /**
     * 是否显示Title
     */
    fun setTiyendeTextTitleVisibility(visibility: Int){
        rootViewBinding.rootTitle.visibility = visibility
    }

    /**
     * 设置Title颜色
     */
    fun setTiyendeTextTitleColor(color: Int) {
        setTiyendeTextTitleVisibility(View.VISIBLE)
        rootViewBinding.rootTitle.setTextColor(color)
    }

    /**
     * 设置Title
     */
    fun setTiyendeTextTitle(text: String) {
        setTiyendeTextTitleVisibility(View.VISIBLE)
        rootViewBinding.rootTitle.text = text
    }

    /**
     * 设置Title对齐方式
     * 默认：Gravity.LEFT
     */
    fun setTiyendeTextTitleGravity(gravity: Int){
        setTiyendeTextTitleVisibility(View.VISIBLE)
        rootViewBinding.rootTitle.gravity = gravity
    }

    /**
     * 设置是否显示右侧图标
     */
    private fun setTiyendeRightBtnVisibility(visibility: Int){
        rootViewBinding.rootCustomer.visibility = visibility
    }

    /**
     * 设置右侧按钮图标
     */
    fun setTiyendeRightBtnRes(res: Int){
        setTiyendeRightBtnVisibility(View.VISIBLE)
        rootViewBinding.rootCustomer.setImageResource(res)
    }

    override fun getContext(): Context {
        return this
    }

    override fun showTiyendeLoading() {
        showTiyendeLoading(isTOuchOut = false, isCancel = true)
    }

    fun showTiyendeLoading(msg: String="") {
        showTiyendeLoading(isTOuchOut = false, isCancel = true,msg)
    }

    fun showTiyendeLoading(isTOuchOut: Boolean, isCancel: Boolean, msg: String="") {
        TiyendeLoading.show(this, isTOuchOut, isCancel,msg)
    }

    override fun hiddenTiyendeLoading() {
        TiyendeLoading.dismiss(this)
    }

    /**
     * toast
     * @param msg
     */
    override fun showTiyendeToast(msg: String?) {
        TiyendeToastManager.showShortText(this, msg)
    }

    /**
     * toast
     * @param msg
     */
    fun showTiyendeToastDuration(msg: String?, duration: Int) {
        TiyendeToastManager.showTextDuration(this, msg, duration)
    }

    /**
     * 设置退出程序提示语
     */
    fun setExitTips(tips: String){
        this.mExitTips = tips
    }

    /**
     * 页面跳转（不带参数）
     *
     * @param T
     */
    open fun onIntent(T: Class<*>?) {
        startActivity(Intent(this, T))
    }

    /**
     * 页面跳转（带参数）
     *
     * @param T
     * @param bundle
     */
    open fun onIntent(T: Class<*>?, bundle: Bundle?) {
        val intent = Intent(this, T)
        if (bundle != null) intent.putExtras(bundle)
        startActivity(intent)
    }

    /* 隐藏键盘 */
    fun onHideSoftInput(v: View) {
        val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(v.windowToken, 0)
    }

    /**
     * 隐藏软键盘
     */
    fun onHideSoftInput() {
        val window = this.window
        var view = window.currentFocus
        if (view == null){
            view = window.decorView
        }
        onHideSoftInput(view)
    }

    /* 显示键盘 */
    fun onShowSoftInput(v: View?) {
        val inputMethodManager = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
        inputMethodManager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS)
        v?.requestFocus()
    }

    /**
     * 点击外部隐藏键盘
     * 滑动不隐藏
     */
    private var downY = 0.0f
    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        when(ev.action){
            MotionEvent.ACTION_DOWN -> {
                downY = ev.y
            }
            MotionEvent.ACTION_UP -> {
                // 获得当前得到焦点的View，一般情况下就是EditText（特殊情况就是轨迹求或者实体案件会移动焦点）
                val v = currentFocus
                if (isShouldHideInput(v, ev) && isHideSoftInput && downY == ev.y) {
                    hideSoftInput(v?.windowToken)
                }
            }
        }
        return super.dispatchTouchEvent(ev)
    }

    /**
     * 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘，因为当用户点击EditText时没必要隐藏
     *
     * @param v
     * @param event
     * @return
     */
    private fun isShouldHideInput(v: View?, event: MotionEvent): Boolean {
        if (v != null && v is EditText) {
            val l = intArrayOf(0, 0)
            v.getLocationInWindow(l)
            val left = l[0]
            val top = l[1]
            val bottom = top + v.getHeight()
            val right = (left + v.getWidth())
            return if (event.x > left && event.x < right && event.y > top && event.y < bottom) {
                // 点击EditText的事件，忽略它。
                false
            } else {
                true
            }
        }
        // 如果焦点不是EditText则忽略，这个发生在视图刚绘制完，第一个焦点不在EditView上，和用户用轨迹球选择其他的焦点
        return false
    }

    /**
     * 多种隐藏软件盘方法的其中一种
     *
     * @param token
     */
    private fun hideSoftInput(token: IBinder?) {
        if (token != null) {
            val im = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
            im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS)
        }
    }

    /* 返回 */
    fun onBackAction() {
        if (!isInterceptBack) { //不拦截，直接返回
            finish()
        }
    }

    /* 是否拦截返回按钮 */
    fun isInterceptBack(isBackExit: Boolean) {
        isInterceptBack = isBackExit
    }

    /* 点击外部是否需要隐藏软键盘 */
    fun isHideSoftInputClickTouchOut(isTouchOut: Boolean){
        isHideSoftInput = isTouchOut
    }

    /* 向Activity中添加fragment */
//    fun addContainerFragement(layout: Int, fragment: BaseFragment?) {
//        if (fragment != null && !fragment.isAdded){
//            supportFragmentManager
//                .beginTransaction()
//                .add(layout, fragment) // 此处的R.id.fragment_container是要盛放fragment的父容器
//                .commitAllowingStateLoss()
//        }
//    }

    /* 替换Activity中的fragment */
    @SuppressLint("CommitTransaction")
    fun replaceContainerFragement(layout: Int, fragment: BaseFragment?) {
        if (fragment != null && !fragment.isAdded){
            supportFragmentManager
                .beginTransaction()
                .replace(layout, fragment) // 此处的R.id.fragment_container是要盛放fragment的父容器
                .commitAllowingStateLoss()
        }
    }

    /* 显示Activity中的fragment */
    @SuppressLint("CommitTransaction")
    fun showContainerFragement(fragment: BaseFragment?) {
        if (fragment != null && fragment.isAdded){
            supportFragmentManager
                .beginTransaction()
                .show(fragment) // 此处的R.id.fragment_container是要盛放fragment的父容器
                .commitAllowingStateLoss()
        }
    }

    /* 隐藏Activity中的fragment */
    @SuppressLint("CommitTransaction")
    fun hideContainerFragement(fragment: BaseFragment?) {
        if (fragment != null && fragment.isAdded){
            supportFragmentManager
                .beginTransaction()
                .hide(fragment) // 此处的R.id.fragment_container是要盛放fragment的父容器
                .commitAllowingStateLoss()
        }
    }

    /* 移除Activity中的fragment */
    @SuppressLint("CommitTransaction")
    fun removeContainerFragement(fragment: BaseFragment?) {
        if (fragment != null && fragment.isAdded){
            supportFragmentManager
                .beginTransaction()
                .remove(fragment) // 此处的R.id.fragment_container是要盛放fragment的父容器
                .commitAllowingStateLoss()
        }
    }

    /**
     * @功能描述：是否连续两次返回退出
     */
    private var isBackExit = false
    fun setBackExit(isBackExit: Boolean) {
        this.isBackExit = isBackExit
    }

    private var exitTime: Long = 0
    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.action == KeyEvent.ACTION_DOWN) {
            if (isBackExit) {
                if (System.currentTimeMillis() - exitTime > 2000) {
                    showTiyendeToast(mExitTips)
                    exitTime = System.currentTimeMillis()
                } else {
//                    System.exit(0);
                    TiyendeActivityStackManager.finishAllActivity()
                }
            } else {
                onBackAction()
            }
            return true
        }
        //        if (keyCode == KeyEvent.KEYCODE_BACK && mActivitys.size() == 1) {
//            startActivity(new Intent("icloudwave.hhour.home"));
//        }
        return super.onKeyDown(keyCode, event)
    }

    override fun onDestroy() {
        super.onDestroy()
//        NetworkUtils.onCancelRequest()
    }
}